package com.xiaoshuidi.cloud.module.rooms.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoshuidi.cloud.framework.common.exception.ServiceException;
import com.xiaoshuidi.cloud.framework.common.exception.enums.GlobalErrorCodeConstants;
import com.xiaoshuidi.cloud.framework.common.pojo.PageResult;
import com.xiaoshuidi.cloud.module.rooms.controller.admin.roomEquipmentrepair.vo.RoomEquipmentRepairResp;
import com.xiaoshuidi.cloud.module.rooms.controller.admin.roomEquipmentrepair.vo.RoomEquipmentRepairVO;
import com.xiaoshuidi.cloud.module.rooms.enums.EquipmentPositionType;
import com.xiaoshuidi.cloud.module.rooms.enums.EquipmentStatus;
import com.xiaoshuidi.cloud.module.rooms.enums.RepairReasonEnum;
import com.xiaoshuidi.cloud.module.rooms.enums.RepairStatusEnum;
import com.xiaoshuidi.cloud.module.rooms.mapper.RoomEquipmentRepairMapper;
import com.xiaoshuidi.cloud.module.rooms.pojo.RoomEquipment;
import com.xiaoshuidi.cloud.module.rooms.pojo.RoomEquipmentRepair;
import com.xiaoshuidi.cloud.module.rooms.repository.RoomEquipmentRepairRepository;
import com.xiaoshuidi.cloud.module.rooms.repository.RoomEquipmentRepository;
import com.xiaoshuidi.cloud.module.rooms.service.RoomEquipmentRepairService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@Validated
@RequiredArgsConstructor
public class RoomEquipmentRepairServiceImpl extends ServiceImpl<RoomEquipmentRepairMapper, RoomEquipmentRepair> implements RoomEquipmentRepairService {

    private final RoomEquipmentRepairRepository roomEquipmentRepairRepository;
    private final RoomEquipmentRepository roomEquipmentRepository;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean create(RoomEquipmentRepairVO vo) {
        RoomEquipment roomEquipment = roomEquipmentRepository.getById(vo.getEquipmentId());
        if (roomEquipment == null) {
            throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(), "资产不存在");
        }
        if (EquipmentStatus.SCRAPPED.getCode().equals(roomEquipment.getStatus())
                || EquipmentStatus.MAINTENANCE.getCode().equals(roomEquipment.getStatus())
                || EquipmentStatus.LOSE.getCode().equals(roomEquipment.getStatus())) {
            throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(), "资产当前状态,不可进行维修");
        }
        RoomEquipmentRepair roomEquipmentRepair = new RoomEquipmentRepair();
        BeanUtils.copyProperties(vo, roomEquipmentRepair);
        roomEquipmentRepair.setStatus(RepairStatusEnum.INMAINTENANCE.getCode());
        //变更资产状态
        roomEquipment.setStatus(EquipmentStatus.MAINTENANCE.getCode());
        this.baseMapper.insert(roomEquipmentRepair);
        roomEquipmentRepository.updateById(roomEquipment);
        //todo 需要创建维修工单
        return true;
    }

    @Override
    public List<RoomEquipmentRepairResp> listByEquipmentId(Long equipmentId) {
        List<RoomEquipmentRepair> list = roomEquipmentRepairRepository.listByEquipmentId(equipmentId);
        List<RoomEquipmentRepairResp> collect = list.stream().map(r -> {
            RoomEquipmentRepairResp resp = convert(r);
            return resp;
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public RoomEquipmentRepairVO getById(Long id) {
        RoomEquipmentRepair repair = this.baseMapper.selectById(id);
        RoomEquipmentRepairVO vo = new RoomEquipmentRepairVO();
        BeanUtils.copyProperties(repair, vo);
        if (StringUtils.isNotEmpty(repair.getRepairReason())) {
            vo.setRepairReason(RepairReasonEnum.getNameByCode(repair.getRepairReason()));
        }
        if (StringUtils.isNotEmpty(repair.getStatus())) {
            vo.setStatus(RepairStatusEnum.getNameByCode(repair.getStatus()));
        }
        vo.setBeginDateStr(LocalDateTimeUtil.format(repair.getBeginDate(), "yyyy-MM-dd HH:mm:ss"));
        vo.setEndDateStr(LocalDateTimeUtil.format(repair.getEndDate(), "yyyy-MM-dd HH:mm:ss"));
        return vo;
    }

    @Override
    public Boolean deleteById(Long id) {
        //todo 资产不可以删除
//        this.baseMapper.deleteById(id);
        return true;
    }

    @Override
    public Boolean updateStateById(Long id) {
        RoomEquipmentRepair repair = roomEquipmentRepairRepository.getById(id);
        roomEquipmentRepairRepository.updateStateById(id);
        Long equipmentId = repair.getEquipmentId();
        RoomEquipment roomEquipment = roomEquipmentRepository.getById(equipmentId);
        if (!EquipmentStatus.SCRAPPED.getCode().equals(roomEquipment.getStatus()) && !EquipmentStatus.LOSE.getCode().equals(roomEquipment.getStatus())) {
            if (roomEquipment.getPositionType().equals(String.valueOf(EquipmentPositionType.STORE_ROOM.getCode()))) {
                roomEquipment.setStatus(String.valueOf(EquipmentStatus.LEAVE_UNUSED.getCode()));
            } else {
                roomEquipment.setStatus(String.valueOf(EquipmentStatus.INUSE.getCode()));
            }
            roomEquipmentRepository.updateById(roomEquipment);
        }
        return true;
    }

    @Override
    public PageResult<RoomEquipmentRepairResp> page(Long equipmentId, int pageNum, int pageSize) {
        Page<RoomEquipmentRepair> page = Page.of(pageNum, pageSize);
        LambdaQueryWrapper<RoomEquipmentRepair> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(RoomEquipmentRepair::getEquipmentId, equipmentId)
                .orderByDesc(RoomEquipmentRepair::getId);
        page = this.roomEquipmentRepairRepository.page(page, wrapper);
        List<RoomEquipmentRepair> records = page.getRecords();
        List<RoomEquipmentRepairResp> resps = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(records)) {
            resps = records.stream().map(s -> {
                RoomEquipmentRepairResp resp = convert(s);
                return resp;
            }).collect(Collectors.toList());
        }
        return new PageResult<>(resps, page.getTotal());
    }

    public RoomEquipmentRepairResp convert(RoomEquipmentRepair bean) {
        RoomEquipmentRepairResp resp = new RoomEquipmentRepairResp();
        BeanUtils.copyProperties(bean, resp);
        if (StringUtils.isNotEmpty(bean.getRepairReason())) {
            resp.setRepairReason(RepairReasonEnum.getNameByCode(bean.getRepairReason()));
        }
        if (StringUtils.isNotEmpty(bean.getStatus())) {
            resp.setStatus(RepairStatusEnum.getNameByCode(bean.getStatus()));
        }
        resp.setBeginDateStr(LocalDateTimeUtil.format(bean.getBeginDate(), "yyyy-MM-dd HH:mm:ss"));
        resp.setEndDateStr(LocalDateTimeUtil.format(bean.getEndDate(), "yyyy-MM-dd HH:mm:ss"));
        return resp;
    }

}
